package com.leehom.arch.base.redis.client.serializer;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;

/**
 * Redis序列化 ObjectOutputStream实现
 * 
 * @author zhugj
 * @date 2018年5月22日 下午2:03:29
 * @version 1.0.0
 */
public class RedisSerializerObjectOutputStreamImpl implements RedisSerializer<Object> {
	
    @Override
    public byte[] serialize(Object obj) throws SerializationException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream oos;
		try {
			oos = new ObjectOutputStream(baos);
	        oos.writeObject(obj);
	        return baos.toByteArray();
		} catch (IOException e) {
			throw new SerializationException("IOException", e.getCause());
		}

    }

    @Override
    public Object deserialize(byte[] bytes) throws SerializationException {
    	ByteArrayInputStream bais = null;
        try {
            bais = new ByteArrayInputStream(bytes);
            ObjectInputStream ois = new ObjectInputStream(bais);
            return ois.readObject();
        } catch (IOException | ClassNotFoundException e) {
        	throw new SerializationException(e.getClass().getName(), e.getCause());
        }
    }
    
}
